package com.cskaoyan.service.wx_footprint;

import com.cskaoyan.bean.goods.Goods;
import com.cskaoyan.bean.user.Footprint;
import com.cskaoyan.bean.user.FootprintExample;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wx_footprint.exception.DeleteFootprintException;
import com.cskaoyan.bean.wx_footprint.base.FootprintPageData;
import com.cskaoyan.bean.wx_footprint.base.FootprintParam;
import com.cskaoyan.bean.wx_footprint.vo.FootprintListVo;
import com.cskaoyan.mapper.goods.GoodsMapper;
import com.cskaoyan.mapper.user.FootprintMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author liXiaoFei
 * @date 2021/10/21 20:57
 */
@Service
public class FootprintServiceImpl implements FootprintService{

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public FootprintPageData queryFootprintListByUser(FootprintParam footprintParam, User user) {
        FootprintExample example = new FootprintExample();
        FootprintExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        example.setOrderByClause("add_time desc");
        List<Footprint> footprints = footprintMapper.selectByExample(example);
        ArrayList<FootprintListVo> footprintListVos = new ArrayList<>();
        ArrayList<Integer> goodsIds = new ArrayList<>();


        for (Footprint footprint : footprints) {
            Goods goods = goodsMapper.selectByPrimaryKey(footprint.getGoodsId());
            if (goodsIds.size() == 0){
                FootprintListVo footprintListVo = new FootprintListVo(goods.getBrief(), goods.getPicUrl(), footprint.getAddTime(), footprint.getGoodsId(), goods.getName(), footprint.getId(), goods.getRetailPrice());
                footprintListVos.add(footprintListVo);
                goodsIds.add(footprint.getGoodsId());
            }
            if (goodsIds.size() != 0 && !goodsIds.contains(footprint.getGoodsId())){
                FootprintListVo footprintListVo = new FootprintListVo(goods.getBrief(), goods.getPicUrl(), footprint.getAddTime(), footprint.getGoodsId(), goods.getName(), footprint.getId(), goods.getRetailPrice());
                footprintListVos.add(footprintListVo);
                goodsIds.add(footprint.getGoodsId());
            }
        }

        return FootprintPageData.ok(footprintListVos);
    }

    @Override
    public void deleteFootprintById(Integer id) throws DeleteFootprintException {
        Footprint footprint = new Footprint();
        footprint.setId(id);
        footprint.setDeleted(true);
        int code = footprintMapper.updateByPrimaryKeySelective(footprint);
        if (code == 0) throw new DeleteFootprintException();
    }


}
